#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ui.h"

// 全局变量
extern lv_obj_t *ui_TextArea3;  // 用户名输入框
extern lv_obj_t *ui_TextArea4;  // 密码输入框
extern lv_obj_t *ui_TextArea5;  // Screen4的文本框1
extern lv_obj_t *ui_TextArea6;  // Screen4的文本框2
extern lv_obj_t *ui_TextArea7;  // Screen4的文本框3
extern lv_obj_t *ui_TextArea8;  // Screen4的文本框4
extern lv_obj_t *ui_Button3;    // 登录按钮
extern lv_obj_t *ui_Button4;    // Screen4的确认按钮
extern lv_obj_t *ui_Screen3;    // 目标屏幕
extern lv_obj_t *ui_Screen4;    // Screen4

extern lv_obj_t *ui_Calendar1;    // 日历控件
extern lv_obj_t *ui_TextArea13;   // 显示天数的文本框
extern lv_obj_t *ui_TextArea14;   // 显示小时的文本框

// 本地全局变量
static lv_obj_t *kb = NULL;     // 键盘对象
static lv_obj_t *error_label = NULL;
static lv_obj_t *current_kb_parent = NULL; // 当前键盘的父对象
static lv_timer_t *time_update_timer = NULL;

// 函数声明
static void hide_error_timer_cb(lv_timer_t *timer);
static void button1_event_handler(lv_event_t *e);
static void hide_keyboard(void);
static void ta_event_cb(lv_event_t *e);
static void check_input_complete();
static int compare_dates(const void *a, const void *b);
void setup_ui(void);

// 最大支持选中的日期数量
#define MAX_SELECTED_DATES 31

// 日期比较函数，用于qsort排序
static int compare_dates(const void *a, const void *b) {
    const lv_calendar_date_t *date1 = (const lv_calendar_date_t *)a;
    const lv_calendar_date_t *date2 = (const lv_calendar_date_t *)b;
    
    // 1. 比较年份
    if(date1->year < date2->year) return -1;
    if(date1->year > date2->year) return 1;
    
    // 2. 年份相同则比较月份
    if(date1->month < date2->month) return -1;
    if(date1->month > date2->month) return 1;
    
    // 3. 年月相同则比较日
    if(date1->day < date2->day) return -1;
    if(date1->day > date2->day) return 1;
    
    // 完全相同
    return 0;
}

// 存储选中日期的数组和计数
static lv_calendar_date_t selected_dates[MAX_SELECTED_DATES];
static uint16_t selected_count = 0;

// 添加或移除选中日期
static void toggle_date_selection(const lv_calendar_date_t *date) {
    if(date->year == 0) return;  // 无效日期
    
    for(uint16_t i = 0; i < selected_count; i++) {
        if(memcmp(&selected_dates[i], date, sizeof(lv_calendar_date_t)) == 0) {
            // 移除日期
            memmove(&selected_dates[i], &selected_dates[i+1], 
                   (selected_count - i - 1) * sizeof(lv_calendar_date_t));
            selected_count--;
            return;
        }
    }
    
    if(selected_count < MAX_SELECTED_DATES) {
        memcpy(&selected_dates[selected_count], date, sizeof(lv_calendar_date_t));
        selected_count++;
    }
}


// 更新日历高亮显示
static void update_calendar_highlight() {
    if(selected_count > 0) {
        lv_calendar_set_highlighted_dates(ui_Calendar1, selected_dates, selected_count);
    } else {
        // 清空高亮
        lv_calendar_set_highlighted_dates(ui_Calendar1, NULL, 0);
    }
}

// 计算选中日期的天数范围
static void calculate_days_range() {
    if(selected_count == 0) {
        lv_textarea_set_text(ui_TextArea13, "0");
        lv_textarea_set_text(ui_TextArea14, "0");
        return;
    }

    // 排序日期数组
    qsort(selected_dates, selected_count, sizeof(lv_calendar_date_t), 
          compare_dates);

    // 直接取首尾日期计算差值
    struct tm start = {0}, end = {0};
    start.tm_year = selected_dates[0].year - 1900;
    start.tm_mon = selected_dates[0].month - 1;
    start.tm_mday = selected_dates[0].day;
    
    end.tm_year = selected_dates[selected_count-1].year - 1900;
    end.tm_mon = selected_dates[selected_count-1].month - 1;
    end.tm_mday = selected_dates[selected_count-1].day;
    
    time_t t1 = mktime(&start);
    time_t t2 = mktime(&end);
    int days = (int)(difftime(t2, t1) / 86400) + 1;
    
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", days);
    lv_textarea_set_text(ui_TextArea13, buf);
    snprintf(buf, sizeof(buf), "%d", days * 24);
    lv_textarea_set_text(ui_TextArea14, buf);
}

// 日历点击事件处理
static void calendar_event_handler(lv_event_t *e) {
    lv_calendar_date_t clicked_date;
    if(lv_calendar_get_pressed_date(ui_Calendar1, &clicked_date)) {
        // 切换选中状态
        toggle_date_selection(&clicked_date);
        
        // 更新高亮显示
        update_calendar_highlight();
        
        // 重新计算天数
        calculate_days_range();
        
        // 强制刷新日历显示
        lv_obj_invalidate(ui_Calendar1);
    }
}

// 设置日历显示当前日期
static void init_calendar_with_current_date() {
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    
    lv_calendar_date_t today;
    today.year = tm_info->tm_year + 1900;
    today.month = tm_info->tm_mon + 1;
    today.day = tm_info->tm_mday;
    
    // 设置日历显示当前月份
    lv_calendar_set_showed_date(ui_Calendar1, today.year, today.month);
}

// 初始化日历
void init_calendar() {
    selected_count = 0; // 重置选中计数
    
    // 设置当前日期
    init_calendar_with_current_date();
    
    // 绑定事件
    lv_obj_add_event_cb(ui_Calendar1, calendar_event_handler, LV_EVENT_VALUE_CHANGED, NULL);
}

// 隐藏键盘
static void hide_keyboard(void) {
    if (kb) {
        lv_keyboard_set_textarea(kb, NULL);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    }
}

// 更新时间显示
static void update_time_display(lv_timer_t *timer) {
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    
    // 1. 更新日期（YYYY-MM-DD）
    char date_str[20];
    strftime(date_str, sizeof(date_str), "%Y-%m-%d", tm_info);
    lv_label_set_text(ui_Label3, date_str);
	lv_label_set_text(ui_Label51, date_str);
	lv_label_set_text(ui_Label54, date_str);
	lv_label_set_text(ui_Label57, date_str);
	lv_label_set_text(ui_Label63, date_str);
	lv_label_set_text(ui_Label66, date_str);
	lv_label_set_text(ui_Label69, date_str);
	lv_label_set_text(ui_Label72, date_str);
	lv_label_set_text(ui_Label75, date_str);
    
    // 2. 更新星期（Mon, Tue...）
    char weekday_str[10];
    strftime(weekday_str, sizeof(weekday_str), "%a", tm_info);
    lv_label_set_text(ui_Label4, weekday_str);
	lv_label_set_text(ui_Label52, weekday_str);
	lv_label_set_text(ui_Label55, weekday_str);
	lv_label_set_text(ui_Label58, weekday_str);
	lv_label_set_text(ui_Label64, weekday_str);
	lv_label_set_text(ui_Label67, weekday_str);
	lv_label_set_text(ui_Label70, weekday_str);
	lv_label_set_text(ui_Label73, weekday_str);
	lv_label_set_text(ui_Label76, weekday_str);
    
    // 3. 更新时间（HH:MM:SS）
    char time_str[10];
    strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_info);
    lv_label_set_text(ui_Label5, time_str);
	lv_label_set_text(ui_Label53, time_str);
	lv_label_set_text(ui_Label56, time_str);
	lv_label_set_text(ui_Label59, time_str);
	lv_label_set_text(ui_Label65, time_str);
	lv_label_set_text(ui_Label68, time_str);
	lv_label_set_text(ui_Label71, time_str);
	lv_label_set_text(ui_Label74, time_str);
	lv_label_set_text(ui_Label77, time_str);
}

void init_auto_time_update() {
    // 如果定时器不存在，就创建它（每秒更新一次）
    if (!time_update_timer) {
        time_update_timer = lv_timer_create(update_time_display, 1000, NULL);
        lv_timer_set_repeat_count(time_update_timer, -1);  // 无限循环
    }
    
    // 立即更新一次，避免初始延迟
    update_time_display(NULL);
}

static void ta_event_cb(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);
    lv_obj_t *parent_screen = lv_obj_get_screen(ta);

    // 只处理目标文本框
    if (ta != ui_TextArea3 && ta != ui_TextArea4 && 
        ta != ui_TextArea5 && ta != ui_TextArea6 && 
        ta != ui_TextArea7 && ta != ui_TextArea8 ) {
        return;
    }

    // 如果键盘未创建或父屏幕已切换，则重新创建键盘
    if (kb == NULL || parent_screen != current_kb_parent) {
        if (kb) lv_obj_del(kb);
        kb = lv_keyboard_create(parent_screen);
        lv_obj_set_size(kb, LV_PCT(100), LV_PCT(40));
        lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        current_kb_parent = parent_screen;
    }

    if (code == LV_EVENT_CLICKED || code == LV_EVENT_FOCUSED) {
        lv_keyboard_set_textarea(kb, ta);
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(kb);
    } 
    else if (code == LV_EVENT_DEFOCUSED || code == LV_EVENT_READY) {
        hide_keyboard();
    }
}

// 修改后的检查输入函数
static void check_input_complete() {
    const char *user = lv_textarea_get_text(ui_TextArea3);
    const char *pwd = lv_textarea_get_text(ui_TextArea4);
    
    if (user && pwd && strlen(user) > 0 && strlen(pwd) > 0) {
        // 有输入时检查账号密码
        if (strcmp(user, "123456GZ") == 0 && strcmp(pwd, "11112222") == 0) {
            lv_obj_clear_state(ui_Button3, LV_STATE_DISABLED);
        } else {
            lv_obj_add_state(ui_Button3, LV_STATE_DISABLED);
        }
    } else {
        // 无输入时禁用按钮
        lv_obj_add_state(ui_Button3, LV_STATE_DISABLED);
    }
}

// 登录按钮事件处理
static void button1_event_handler(lv_event_t *e) {
    hide_keyboard();
    const char *username = lv_textarea_get_text(ui_TextArea3);
    const char *password = lv_textarea_get_text(ui_TextArea4);

    if (!username || !password || strlen(username) == 0 || strlen(password) == 0) {
        if (!error_label) {
            error_label = lv_label_create(lv_scr_act());
            lv_obj_set_style_text_color(error_label, lv_color_hex(0xFF0000), LV_PART_MAIN);
            lv_obj_align(error_label, LV_ALIGN_TOP_MID, 0, 20);
        }
        lv_label_set_text(error_label, "Please input username and password");
        lv_obj_clear_flag(error_label, LV_OBJ_FLAG_HIDDEN);
        lv_timer_create(hide_error_timer_cb, 3000, NULL);
        return;
    }

    if (strcmp(username, "123456GZ") == 0 && strcmp(password, "11112222") == 0) {
        lv_obj_t *target_screen = ui_Screen3;
        _ui_screen_change(&target_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    } else {
        if (!error_label) {
            error_label = lv_label_create(lv_scr_act());
            lv_obj_set_style_text_color(error_label, lv_color_hex(0xFF0000), LV_PART_MAIN);
            lv_obj_align(error_label, LV_ALIGN_TOP_MID, 0, 20);
        }
        lv_label_set_text(error_label, "Account or password error");
        lv_obj_clear_flag(error_label, LV_OBJ_FLAG_HIDDEN);
        lv_timer_create(hide_error_timer_cb, 3000, NULL);
    }
}

// Screen4 确认按钮事件
static void confirm_button_handler(lv_event_t *e) {
    hide_keyboard();
}

static void hide_error_timer_cb(lv_timer_t *timer) {
    if (error_label) {
        lv_obj_add_flag(error_label, LV_OBJ_FLAG_HIDDEN);
    }
    lv_timer_del(timer);
}

void get_user(lv_event_t *e) {
	setup_ui();
}

void get_password(lv_event_t *e) {
    setup_ui();
}

void setup_ui() {
    static bool is_initialized = false;
    if (is_initialized) return;
    is_initialized = true;

    init_calendar();
     // 初始显示0
    lv_textarea_set_text(ui_TextArea13, "0");
    lv_textarea_set_text(ui_TextArea14, "0");
    
    // 绑定Screen2的事件
    lv_obj_add_event_cb(ui_TextArea3, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea4, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_Button3, button1_event_handler, LV_EVENT_CLICKED, NULL);

    // 绑定Screen4的事件
    lv_obj_add_event_cb(ui_TextArea5, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea6, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea7, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea8, ta_event_cb, LV_EVENT_ALL, NULL);
    
    // 绑定Screen5的事件
    lv_obj_add_event_cb(ui_Button4, confirm_button_handler, LV_EVENT_CLICKED, NULL);

	// 新增：设置密码框为加密显示（显示为*）
    lv_textarea_set_password_mode(ui_TextArea4, true);       // 启用密码模式
    lv_textarea_set_password_bullet(ui_TextArea4, "*");     // 设置显示的字符为*
    lv_textarea_set_one_line(ui_TextArea4, true);           // 强制单行输入

    // 初始化日历显示当前日期
    init_calendar_with_current_date();
}

// 空函数（保持兼容性）
void init_datetime_display(void) {}

void get_department1(lv_event_t * e)
{

}

void get_Number1(lv_event_t * e)
{

}

void get_Sex1(lv_event_t * e)
{

}

void get_name1(lv_event_t * e)
{

}

void get_times1(lv_event_t * e)
{

}

void get_times2(lv_event_t * e)
{

}

void get_Name1(lv_event_t * e) {
    // 1. 安全检查
    if (!ui_TextArea7 || !ui_TextArea8 || !ui_TextArea15) {
        printf("Error: UI elements not initialized!\n");
        return;
    }

    // 2. 获取性别和姓名
    const char* gender = lv_textarea_get_text(ui_TextArea7);
    const char* name = lv_textarea_get_text(ui_TextArea8);

    // 3. 如果是"boy"则设置文本到ui_TextArea15
    if (gender && name && strcmp(gender, "boy") == 0) {
        lv_textarea_set_text(ui_TextArea15, name);  // 关键修改：使用文本区域API
    } else {
        lv_textarea_set_text(ui_TextArea15, "Not a boy");
    }
}

void get_Times1(lv_event_t * e)
{

}

void get_nextname1(lv_event_t * e)
{

}

void get_department2(lv_event_t * e)
{

}

void get_Number2(lv_event_t * e)
{

}

void get_Sex2(lv_event_t * e)
{

}

void get_name2(lv_event_t * e)
{

}

void get_Name2(lv_event_t * e)
{

}

void get_Times2(lv_event_t * e)
{

}

void get_nextname2(lv_event_t * e)
{

}

